package com.lhkj.ct.base.mybatis.type;

import com.lhkj.ct.base.utils.EncryptionUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 数据库加密解密
 */
public class DataEncryptHandler implements TypeHandler<String> {
    private static final Logger log = LoggerFactory.getLogger(DataEncryptHandler.class);

    public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        if (StringUtils.isEmpty(parameter)) {
            ps.setString(i, (String)null);
        } else {
            try {
                parameter = EncryptionUtil.encryptString(parameter, EncryptionUtil.publicKey);
            } catch (Exception var6) {
                throw new RuntimeException(var6);
            }
            ps.setString(i, parameter);
        }
    }

    public String getResult(ResultSet rs, String columnName) throws SQLException {
        return this.decrypt(rs.getString(columnName));
    }

    public String getResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.decrypt(rs.getString(columnIndex));
    }

    public String getResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.decrypt(cs.getString(columnIndex));
    }

    public String decrypt(String value) {
        if (null == value) {
            return null;
        } else {
            try {
                return EncryptionUtil.decryptString(value, EncryptionUtil.privateKey);
            } catch (Exception var3) {
                log.error(ExceptionUtils.getStackTrace(var3));
                return value;
            }
        }
    }
}
